介绍
curses 将终端屏幕看成是由字符单元组成的网格, 每一个单元有(行,列)坐标对标示 . 坐标系的原点是屏幕的左上角, 坐标自上而下递增, 列坐标自左向右递增.
curses 具有函数包括可以将光标移动到屏幕上任何行.列单元, 添加字符到屏幕或者 从屏幕上删除字符, 设置字符的可视属性(颜色,亮度等), 建立和控制窗口以及其他 文本域
基本 curses 函数 | |
---|---|
initscr() | 初始化 curses 库和 tty |
endwin() | 关闭 curses 并重置 tty |
refresh() | 使屏幕按照你的意图显示 |
move(r,c) | 将光标移动到屏幕的(r,c)位置 |
addstr(s) | 在当前位置画字符串 s |
addch(c) | 在当前位置画字符 c |
clear() | 清屏 |
standout() | 启动 standout 模式(一般使屏幕反色) |
standend() | 关闭 standout 模式 |
例子
hello1.c
#include <stdio.h> #include <curses.h> int main() { initscr(); clear(); move(10, 20); addstr("Hello, world"); move(LINES - 1, 0); refresh(); getch(); endwin(); return 0; }
- 编译
cc hello1.c -o hello1 -lcurses
hello2.c
#include <stdio.h> #include <curses.h> int main(){ int i; initscr(); clear(); for (i = 0; i < LINES; i++){ move(i, i + i); if (i % 2 == 1) standout(); addstr("Hello, world!"); if (i % 2 == 1) standend(); } refresh(); getch(); endwin(); return 0; }
curses 内部: 虚拟和实际屏幕
curses 设计称为能够在不阻塞通信线路的情况下更新文本屏幕。 curses 通过虚拟屏幕来最小化数据流量。
真实屏幕是眼前的一个字符数组. curses 保留了屏幕的两个内部版本. 一个内部屏幕是真实屏幕的复制. 另一个是工作屏幕, 其上记录了对屏幕的改动. 每个函数, 比如 move, addstr 等都只在工作屏幕上尽心刚修改. 工作屏幕就像磁盘缓冲, curses中的大部分函数都只对它进行修改.
refresh 函数比较两个屏幕的差异. 然后通过终端驱动送出哪些能使真实屏幕与工 作屏幕一直的字符和控制码